import { defineStore } from "pinia";
import { findPagerUserClient, getCategoryTreeClient, findByCode, requestFlotPieData } from "@/api/modules/eventManagement";
import { findMySupportITSOPUserPager, findAllClienk, getCategoryTreeAllData, getCategoryTree } from "@/api/modules/common";
import { useUserStore } from "./user";

interface TreeNode {
  attr?: Record<string, any>; // attr 是一个可选的对象，键是字符串，值是任意类型
  children?: TreeNode[]; // children 是一个可选的 TreeNode 数组
}

function flattenAttr(nodes: TreeNode[]): TreeNode[] {
  return nodes.map(node => {
    const result: TreeNode = {
      children: node.children ? flattenAttr(node.children) : []
    };

    if (node.attr) {
      // 使用对象解构和展开运算符将 attr 的内容复制到 result 对象中
      // 注意：这里会覆盖 result 对象中可能已存在的同名属性（如果有的话）
      Object.assign(result, node.attr);
    }

    // 由于我们已经明确设置了 children，所以这里不需要再检查 undefined
    return result;
  });
}

interface optionsItem {
  orgList: any;
  userList: any;
  cateList: any;
  imodeList: any;
  priorityList: any;
  effectRangeList: any;
  levelList: any;
  seriousnessList: any;
  groupList: TreeNode[];
  statusList: any;
  positionList: any;
  slaStatusList: any;
  serviceList: TreeNode[];
}

export const requestAllOptions = defineStore({
  id: "event-options",
  state: (): optionsItem => ({
    orgList: [], // 所属客户列表
    userList: [], // 请求人列表
    cateList: [], // 分类列表
    imodeList: [], // 来源列表
    priorityList: [], // 优先级列表
    effectRangeList: [], // 影响列表
    levelList: [], // 复杂程度表
    seriousnessList: [], // 紧急度列表
    groupList: [], // 指派组列表
    statusList: [], // 状态列表
    positionList: [], // 位置列表
    slaStatusList: [], // sla状态列表
    serviceList: [] // 服务目录
  }),
  getters: {},
  actions: {
    // 获取请求人列表
    getUserList(companyNo: number) {
      findPagerUserClient({
        "userQueryDto.companyNo": companyNo,
        "userQueryDto.loginName": "",
        Sord: "desc",
        sidx: "userId",
        _search: false,
        page: 1,
        rows: 100
      }).then((res: any) => {
        this.userList = res.data || [];
      });
    },
    async getAllOptions() {
      // 获取所属客户列表
      const userStore = useUserStore();
      await findMySupportITSOPUserPager({
        "itsopUserQueryDTO.loginName": userStore.username,
        sidx: "orgNo",
        sord: "desc",
        page: 1,
        rows: 10
      }).then((res: any) => {
        let list = res.data || [];
        list.forEach(item => {
          item.label = [item.orgName, item.officePhone, item.email, item.address].join(" / ");
        });
        this.orgList = list;
      });
      // 获取分类列表
      await getCategoryTreeClient({
        types: "request",
        parentEventId: 0
      }).then((res: any) => {
        this.cateList = res.children || [];
      });
      // 获取来源列表
      await findByCode({
        "dataDictionaryQueryDto.groupCode": "imode"
      }).then((res: any) => {
        let list = res || [];
        this.imodeList = list;
      });
      // 获取优先级列表
      await findByCode({
        "dataDictionaryQueryDto.groupCode": "priority"
      }).then((res: any) => {
        let list = res || [];
        this.priorityList = list;
      });
      // 获取影响列表
      await findByCode({
        "dataDictionaryQueryDto.groupCode": "effectRange"
      }).then((res: any) => {
        let list = res || [];
        this.effectRangeList = list;
      });
      // 获取复杂程度表
      await findByCode({
        "dataDictionaryQueryDto.groupCode": "level"
      }).then((res: any) => {
        let list = res || [];
        this.levelList = list;
      });
      // 获取紧急度列表
      await findByCode({
        "dataDictionaryQueryDto.groupCode": "seriousness"
      }).then((res: any) => {
        let list = res || [];
        this.seriousnessList = list;
      });
      // 位置列表
      await getCategoryTreeAllData({
        flag: "dataDic",
        types: "Location",
        parentEventId: 0,
        num: 50
      }).then((res: any) => {
        let list = res.children || [];
        this.positionList = list;
      });
      // 状态列表
      await requestFlotPieData({
        "requestQueryDTO.countQueryType": "all",
        "requestQueryDTO.groupField": "status",
        "requestQueryDTO.loginName": "admin"
      }).then((res: any) => {
        let list = res || [];
        this.statusList = list;
      });
      // SLA状态列表
      await requestFlotPieData({
        "requestQueryDTO.countQueryType": "all",
        "requestQueryDTO.groupField": "slaState",
        "requestQueryDTO.loginName": "admin"
      }).then((res: any) => {
        let list = res || [];
        this.slaStatusList = list;
      });
      // 服务目录
      await getCategoryTree({
        types: "Service",
        parentEventId: 0,
        num: 0,
        _: new Date().getTime()
      }).then((res: any) => {
        this.serviceList = flattenAttr([res]);
      });
      // 指派组列表
      findAllClienk({
        companyNo: userStore.userInfo.companyNo,
        parentOrgNo: 0,
        _: new Date().getTime()
      }).then((res: any) => {
        console.log(res)
        this.groupList = flattenAttr(res);
        // this.groupList = res;
      });
    }
  }
});
